import tkinter as tk
from tkinter import filedialog, messagebox
from heic2png import HEIC2PNG
import os
import threading


class HEICConverterApp:
    def __init__(self, root):
        self.root = root
        self.root.title("HEIC to PNG 转换器")
        self.root.geometry("600x500")

        self.filepath = ""
        self.files = []

        # 创建菜单栏
        menubar = tk.Menu(root)
        root.config(menu=menubar)

        # 创建文件菜单
        file_menu = tk.Menu(menubar, tearoff=0)
        menubar.add_cascade(label="文件", menu=file_menu)
        file_menu.add_command(label="选择文件夹", command=self.select_folder)
        file_menu.add_command(label="选择文件", command=self.select_file)

        # 创建一个列表框来显示 HEIC 文件
        self.file_listbox = tk.Listbox(root, selectmode=tk.MULTIPLE, width=80, height=20)
        self.file_listbox.pack(pady=20)

        # 绑定双击事件
        self.file_listbox.bind("<Double-1>", self.on_item_double_click)

        # 创建按钮
        button_frame = tk.Frame(root)
        button_frame.pack(pady=10)

        batch_convert_btn = tk.Button(button_frame, text="批量转换", command=self.batch_convert)
        batch_convert_btn.pack(side=tk.LEFT, padx=5)

        convert_btn = tk.Button(button_frame, text="转换", command=self.convert)
        convert_btn.pack(side=tk.LEFT, padx=5)

    def select_folder(self):
        self.filepath = filedialog.askdirectory()
        if not self.filepath:
            return

        self.files = [f for f in os.listdir(self.filepath) if f.lower().endswith(".heic")]
        self.update_file_listbox()

    def select_file(self):
        file = filedialog.askopenfilename(filetypes=[("HEIC files", "*.heic")])
        if file:
            self.filepath = os.path.dirname(file)
            self.files = [os.path.basename(file)]
            self.update_file_listbox()

    def update_file_listbox(self):
        self.file_listbox.delete(0, tk.END)
        for file in self.files:
            self.file_listbox.insert(tk.END, file)

    def batch_convert(self):
        if not self.filepath:
            messagebox.showerror("错误", "请先选择一个文件夹。")
            return

        thread = threading.Thread(target=self._batch_convert)
        thread.start()

    def _batch_convert(self):
        for file in self.files:
            fullpath = os.path.join(self.filepath, file)
            try:
                heic_img = HEIC2PNG(fullpath)
                if "heic" in fullpath.lower():
                    png_path = fullpath.lower().replace(".heic", ".png")
                else:
                    png_path = fullpath.lower().replace(".HEIC", ".png")
                heic_img.save(png_path)
            except Exception as e:
                self.root.after(0, lambda: messagebox.showerror("转换错误", f"{fullpath}: {str(e)}"))

        self.root.after(0, lambda: messagebox.showinfo("成功", "批量转换已完成。"))

    def convert(self):
        selected_indices = self.file_listbox.curselection()
        if not selected_indices:
            messagebox.showerror("错误", "请从列表中选择一个文件。")
            return

        files_to_convert = [self.files[i] for i in selected_indices]

        thread = threading.Thread(target=self._convert_files, args=(files_to_convert,))
        thread.start()

    def _convert_files(self, files_to_convert):
        for file in files_to_convert:
            fullpath = os.path.join(self.filepath, file)
            try:
                heic_img = HEIC2PNG(fullpath)
                heic_img.save(fullpath.replace(".heic", '.png'))
            except Exception as e:
                self.root.after(0, lambda: messagebox.showerror("转换错误", f"{fullpath}: {e}"))

        self.root.after(0, lambda: messagebox.showinfo("成功", "选择的文件已被转换。"))

    def on_item_double_click(self, event):
        selected_indices = self.file_listbox.curselection()
        if not selected_indices:
            return

        file = self.files[selected_indices[0]]
        if messagebox.askyesno("确认", f"是否转换 {file}?"):
            self.convert()  # 调用 convert 方法处理选中的文件


if __name__ == "__main__":
    root = tk.Tk()
    app = HEICConverterApp(root)
    root.mainloop()